/*******************************************************************************
* Copyright (c) 2010, 2017 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.dishes.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.MachiningRelation;
import com.qinyeit.serviceapp.entity.Material;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.dishes.MachiningRelationRepository;
import com.qinyeit.serviceapp.service.dishes.MachiningRelationService;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.lang.StringUtils;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import com.qinyetech.springstage.core.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/** 
 * ClassName: MachiningRelationServiceImpl <br/> 
 * Function: 加工关系明细 业务实现 <br/> 
 * date: 2019-01-24 13:52:07 <br/> 
 * 
 * @author 祁雪萍
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class MachiningRelationServiceImpl extends BaseService<MachiningRelation, Long> implements MachiningRelationService {

	private final String [] materialKeys = {"id","pinyin","spell","no","name","category","goodsSpec","unit","minStock","maxStock","storeMode","purchaseNewPrice","consumeUnit","consumeUnit","consumeRates","orderPriceBom","orderType","stocktakeType","state", "uuid"};
	@Autowired
	private MachiningRelationRepository machiningRelationRepository;
	@Autowired
	private MaterialService materialService;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;


	@Override
	@Transactional
	public void saveMaterial(JSONObject json,Long merchantGroupId) {
		Long productId = json.getLong("productId");
		Material product = materialService.findById(productId);
		if(product==null){
			throw new BusinessRunTimeException("成品不存在", 1001);
		}
		JSONArray items= json.getJSONArray("items");
		if(items==null || items.size()==0){
			throw new BusinessRunTimeException("请选择原料", 1003);
		}
		product.setHasRelation(true);
		product.setUpdateTimestamp(DateUtils.current());
		materialService.update(product);
		deleteDetails(productId);
		MachiningRelation machiningRelation;
		JSONObject item ;
		for(int i=0;i< items.size();i++){
			item = items.getJSONObject(i);
			machiningRelation=new MachiningRelation();
			machiningRelation.setMerchantGroupId(merchantGroupId);
			machiningRelation.setProductId(product.getId());
			machiningRelation.setMaterialId(item.getLong("id"));
			machiningRelation.setCount(item.getDouble("count"));
			this.save(machiningRelation);
		}

	}



	@Transactional
	public void deleteDetails(Long id){
		machiningRelationRepository.deleteById(id);
	}




	/**
	 *
	 * @param dName   成品name或编码
	 * @param mName    原料name或no
	 * @param hasCost   是否添加加工关系
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Map<String, Object>> findAllList(String dName, String mName, Boolean hasCost, Pageable pageable,Long merchantGroupId) {
		String sql ="select * from (SELECT p.*, COUNT(mr.id) AS isCpunt FROM materials p\n" +
				"LEFT JOIN machining_relations mr ON mr.product_id=p.id\n" +
				"LEFT JOIN materials m ON m.id=mr.material_id\n" +
				"WHERE p.material_type='PRODUCT' and  p.is_deleted = 0 AND p.merchant_group_id=:merchant_group_id \n" ;

		QyMap params = QyMap.map("merchant_group_id",merchantGroupId);
		if(StringUtils.isNotBlank(dName)){
			sql+= " AND (p.no LIKE :dname OR p.name LIKE :dname ) ";
			params.setv("dname","%"+dName+"%");
		}

		if(StringUtils.isNotBlank(mName)){
			sql +=  " AND (m.no LIKE :mname OR m.name LIKE :mname ) ";
			params.setv("mname","%"+mName+"%");
		}

		sql +=" GROUP BY p.id, p.no, p.name, p.unit, p.goods_spec)t where 1=1 ";
		if (hasCost!=null && hasCost){
			sql += " and isCpunt>0";
		}
		Page<Map<String,Object>> page = jdbcTemplate.queryForList(sql,params,pageable);
		return page;
	}

    @Override
    public void deleteRelation(Long id,Long merchantGroupId) {
	    Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
	    searchable.addSearchFilter("id", SearchOperator.eq, id);
        Material material = materialService.findOne(searchable);
        if(material!=null){
            material.setHasRelation(false);
            materialService.update(material);
            machiningRelationRepository.deleteById(material.getId());
        }

    }


}